#include <algorithm>

#include <QFileDialog>
#include <QFileInfo>

#include "maemo5settingsgui.h"
#include "ui_maemo5settingsgui.h"
#include "longinputdialog.h"

#include "settings.h"

// TODO perform sanity check of data input

Maemo5SettingsGui::Maemo5SettingsGui(const QList<QString> & licences,
                                     const QString        & app,
                                     QWidget              * parent) :
    QWidget(parent),
    ui(new Ui::Maemo5SettingsGui),
    m_app(app)
{
    ui->setupUi(this);

    ui->m_authorName->setText(Settings::get(Settings::HybridAuthor).toString());
    ui->m_authorEmail->setText(Settings::get(Settings::HybridEmail).toString());
    ui->m_shortDesc->setText(Settings::get(Settings::HybridShortDesc, app).toString());
    ui->m_longDesc->setText(Settings::get(Settings::HybridLongDesc, app).toString());

    // filling up ui->m_licence and selecting default licence (from setttings)
    ui->m_licence->addItems(licences);

    size_t
            licenceIndex = -1;

    if (licences.size() > 0)
    {
        QString
                licence = Settings::get(Settings::Licence).toString();
        QList<QString>::const_iterator
            foundIt = std::find(licences.begin(),
                                licences.end(),
                                licence);
        if (foundIt != licences.end())
        {
            licenceIndex = std::distance(licences.begin(),
                                         foundIt);
        }
    }
    ui->m_licence->setCurrentIndex(licenceIndex);

    ui->m_logFileValue->setText(Settings::get(Settings::LogFilePath).toString());

    QString
        bashPathStr = bashPath();
    if (bashPathStr.length() > 0)
    {
        ui->m_bashPath->setText(bashPathStr);
    }

    ui->m_checkWidgetPannable->setChecked(Settings::get(Settings::PanningEnabled).toBool());
    ui->m_checkTextSelectable->setChecked(Settings::get(Settings::TextSelectionEnabled).toBool());

    // Connect browse buttons
    connect(ui->m_buttonBrowseBash, SIGNAL(clicked()), this, SLOT(browseForBash()));
    connect(ui->m_buttonBrowseLog, SIGNAL(clicked()), this, SLOT(browseForLog()));
    connect(ui->m_longDescButton, SIGNAL(clicked()), this, SLOT(editLongDesc()));
}

Maemo5SettingsGui::~Maemo5SettingsGui()
{
    delete ui;
}

void Maemo5SettingsGui::changeEvent(QEvent *e)
{
    QWidget::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;
    default:
        break;
    }
}


void Maemo5SettingsGui::saveSettings() const
{
    Settings::set(Settings::HybridAuthor, ui->m_authorName->text().trimmed());
    Settings::set(Settings::HybridEmail, ui->m_authorEmail->text().trimmed());
    Settings::set(Settings::HybridShortDesc, ui->m_shortDesc->text().trimmed(), m_app);
    Settings::set(Settings::HybridLongDesc, ui->m_longDesc->text().trimmed(), m_app);

    int
        licenceIndex = ui->m_licence->currentIndex();
    QString
        licence;
    if (licenceIndex != -1)
    {
            licence = ui->m_licence->itemText(licenceIndex);
    }
    Settings::set(Settings::Licence,
                  licence);

    Settings::set(Settings::LogFilePath, ui->m_logFileValue->text().trimmed());

    // see comments in constructor about madde path
    QString
        bashPath = ui->m_bashPath->text().trimmed();
    QRegExp
        bashExeRx("[/\\\\]bash.exe$");
    QString
        maddePath = bashPath.replace(bashExeRx, "");
    if (QFileInfo(maddePath).isDir())
    {
        Settings::set(Settings::MaddePath, maddePath);
    }

    Settings::set(Settings::PanningEnabled, ui->m_checkWidgetPannable->isChecked());
    Settings::set(Settings::TextSelectionEnabled, ui->m_checkTextSelectable->isChecked());
}


void Maemo5SettingsGui::browseForBash()
{
    QString
        bashPath = ui->m_bashPath->text();
    QFileInfo
        bash = getFileInfo(bashPath);

    bashPath = QFileDialog::getOpenFileName(this,
                                            tr("Select path to madde bash.exe"),
                                            bash.absolutePath(),
                                            tr("Bash.exe") + " (bash.exe);;" + tr("All Files (*)"));
    if (!bashPath.isEmpty())
    {
        bashPath = QDir::toNativeSeparators(bashPath);
        ui->m_bashPath->setText(bashPath);
    }
}


void Maemo5SettingsGui::browseForLog()
{
    // Existing
    QFileInfo
        file = getFileInfo(ui->m_logFileValue->text());

    QString
        fileName = QFileDialog::getOpenFileName(this, tr("Select application log file"), file.absolutePath(), tr("Log files") + " (*.log);;" + tr("All Files (*)"));
    if (!fileName.isEmpty())
    {
            fileName = QDir::toNativeSeparators(fileName);
            ui->m_logFileValue->setText(fileName);
    }
}


void Maemo5SettingsGui::editLongDesc()
{
    LongInputDialog
        liDlg(tr("Detail application description"),
              tr("Enter app description:"),
              ui->m_longDesc->text());

    if (liDlg.exec() == QDialog::Accepted)
    {
        ui->m_longDesc->setText(liDlg.contentText());
    }
}


QFileInfo Maemo5SettingsGui::getFileInfo(QString fileName)
{
    QFileInfo file(fileName);
    if (!QFile::exists(file.absolutePath()))
    {
            file = QFileInfo(QDir::root().absolutePath());
    }
    return file;
}


QString Maemo5SettingsGui::bashPath()
{
    // what we store in settings is path to the directory with "bash.exe"
    // and "mad" files - but for clarity, we make the user set the path
    // to bash.exe
    QString
        rv;

    QString
        maddePath = Settings::get(Settings::MaddePath).toString();
    if (maddePath.length() > 0)
    {
        rv = maddePath + QDir::separator() + "bash.exe";
    }

    return rv;
}
